;202230163042��̳�
;�Ƽ�⣬ˮ���⣬������Ĥ

PRO MOD021_Mask,inputfile,outputfie,cloudout,waterout,ndviout
  COMPILE_OPT IDL2
  e = ENVI(/HEADLESS)

  ;�ָ�����ĵ�save�ļ�
  ENVI, /RESTORE_BASE_SAVE_FILES
  ENVI_BATCH_INIT

;  inputfile = 'D:\IDL\data\output\MOD021KM.A2019106.0120.061.2019106132509_BT.dat'
;  outputfie = 'D:\IDL\data\output\MOD021KM.A2019106.0120.061.2019106132509_mask.dat'
;  cloudout = 'D:\IDL\data\output\MOD021KM.A2019106.0120.061.2019106132509_cloud.dat'
;  waterout = 'D:\IDL\data\output\MOD021KM.A2019106.0120.061.2019106132509_water.dat'
;  ndviout = 'D:\IDL\data\output\MOD021KM.A2019106.0120.061.2019106132509_ndvi.dat'
  
  envi_open_file,inputfile,r_fid=fid
  envi_file_query,fid,ns=ns,nl=nl,nb=nb,dims=dims,$
    data_type=data_type,interleave=interleave,offset=offset
  map_info=envi_get_map_info(fid=fid)

  ;read 1 2 7 bands
  ref1=envi_get_data(fid=fid,dims=dims,pos=0)
  ref2=envi_get_data(fid=fid,dims=dims,pos=1)
  ref7=envi_get_data(fid=fid,dims=dims,pos=2)
  ;read 21 31 32 bands
  tb21=envi_get_data(fid=fid,dims=dims,pos=3)
  tb31=envi_get_data(fid=fid,dims=dims,pos=4)
  tb32=envi_get_data(fid=fid,dims=dims,pos=5)

  ;
  ;Cloud detect
  cloud=ref1+ref2 gt 0.9 or tb32 lt 265 $
    or (ref1+ref2 gt 0.7 and tb32 lt 285)
  cloud=ref1 gt 0.25 
  
  ;Water detect
  NDVI=(ref2-ref1)/(ref2+ref1)
  water=ref2 lt 0.15 and ref7 lt 0.05 and ndvi lt 0
  
  ;water= ndvi lt 0
  ;Water
  mask=cloud eq 0 and water eq 0
  
  ENVI_WRITE_ENVI_FILE,mask,out_name=outputfie,map_info=map_info
  ENVI_WRITE_ENVI_FILE,cloud,out_name=cloudout,map_info=map_info
  ENVI_WRITE_ENVI_FILE,water,out_name=waterout,map_info=map_info
  ENVI_WRITE_ENVI_FILE,NDVI,out_name=ndviout,map_info=map_info

  ENVI_FILE_MNG, ID = fid, /REMOVE

  ; Close the ENVI session
  e.Close

  ENVI_BATCH_EXIT

END
